package tclp.gui.panels;

import java.awt.FlowLayout;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import tclp.gui.GUIController;

/**
 *
 * @author Absatz Leoš
 */
public class SettingsScreenPanel extends JPanel {

  private GUIController controller;

  private JTextField imageLoc;

  private JTextField leftUpper;

  private JTextField rightLower;

  private JPanel imagePanel;

  private String screenCoords;

  public SettingsScreenPanel(GUIController controller) {
    this.controller = controller;
    this.screenCoords = controller.getScreenCoords();
    initComponents();
  }

  private void initComponents() {
    this.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    // Label
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    c.insets = new Insets(10, 10, 0, 10);
    c.anchor = GridBagConstraints.NORTHWEST;
    c.weightx = 1;
    JLabel label = new JLabel("Settings Screen");
    this.add(label, c);

    c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 1;
    c.anchor = GridBagConstraints.NORTHWEST;
    c.weightx = 1;
    JPanel selectPanel = new JPanel();
    selectPanel.setLayout(new FlowLayout());

    // Select file
    JLabel selectlabel = new JLabel("Select Image:");
    selectPanel.add(selectlabel);

    imageLoc = new JTextField(40);
    selectPanel.add(imageLoc);

    JButton selectButton = new JButton("Select");
    selectButton.addActionListener(getSelectImageListener());
    selectPanel.add(selectButton);

    // Refresh button
    JButton refreshButton = new JButton("Refresh");
    refreshButton.addActionListener(getRefreshImageListener());
    selectPanel.add(refreshButton);

    // Save settings
    JButton saveButton = new JButton("Save settings");
    saveButton.addActionListener(getSaveListener());
    selectPanel.add(saveButton);

    this.add(selectPanel, c);

    c = new GridBagConstraints();
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 2;
    c.anchor = GridBagConstraints.NORTHWEST;
    c.weightx = 1;
    JPanel cornersPanel = new JPanel();
    cornersPanel.setLayout(new FlowLayout());

    // Left upper corner
    JLabel leftLabel = new JLabel("Left upper corner:");
    cornersPanel.add(leftLabel);
    leftUpper = new JTextField(7);
    leftUpper.setText(initLeft());
    cornersPanel.add(leftUpper);

    // Right lower corner
    JLabel rightLabel = new JLabel("Right lower corner:");
    cornersPanel.add(rightLabel);
    rightLower = new JTextField(7);
    rightLower.setText(initRight());
    cornersPanel.add(rightLower);

    this.add(cornersPanel, c);

    // Scroll Pane
    c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.gridx = 0;
    c.gridy = 3;
    c.anchor = GridBagConstraints.NORTHWEST;
    c.weightx = 1;
    c.weighty = 1;
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    this.add(scrollPane, c);
    imagePanel = new JPanel();
    scrollPane.getViewport().add(imagePanel);
  }

  private ActionListener getSelectImageListener() {
    return new ActionListener() {

      public void actionPerformed(ActionEvent e) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

        int returnVal = chooser.showOpenDialog(null);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
          imageLoc.setText(chooser.getSelectedFile().getAbsolutePath());
        }
      }
    };
  }

  private ActionListener getRefreshImageListener() {
    return new ActionListener() {

      public void actionPerformed(ActionEvent e) {
        String file = imageLoc.getText();
        BufferedImage img = null;
        try {
          img = ImageIO.read(new File(file));
        } catch (IOException ex) {
          Logger.getLogger(SettingsScreenPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        viewImage(img);
      }
    };
  }

  private void viewImage(BufferedImage img) {
    int leftx, lefty, rightx, righty;

    String leftUpperText = leftUpper.getText();
    String[] leftUpperTexts = leftUpperText.trim().split(",");

    try {
      leftx = Integer.parseInt(leftUpperTexts[0]);
      lefty = Integer.parseInt(leftUpperTexts[1]);
    } catch (NumberFormatException e) {
      JOptionPane.showMessageDialog(null, "Error parsing Left upper corner!");
      return;
    }

    String rightLowerText = rightLower.getText();
    String[] rightLowerTexts = rightLowerText.trim().split(",");

    try {
      rightx = Integer.parseInt(rightLowerTexts[0]);
      righty = Integer.parseInt(rightLowerTexts[1]);
    } catch (NumberFormatException e) {
      JOptionPane.showMessageDialog(null, "Error parsing Right lower corner!");
      return;
    }

    ImageFilter filter = new GrayFilter(true, 0);
    ImageProducer producer = new FilteredImageSource(img.getSource(), filter);
    Image grayImage = this.createImage(producer);

    BufferedImage image = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = image.createGraphics();
    g.drawImage(grayImage, 0, 0, null);
    g.drawImage(img, leftx, lefty, rightx, righty, leftx, lefty, rightx, righty, null);
    g.dispose();

    JLabel picLabel = new JLabel(new ImageIcon(image));
    imagePanel.removeAll();
    imagePanel.add(picLabel);
    controller.repaintKeepSize();
  }

  private ActionListener getSaveListener() {
    return new ActionListener() {

      public void actionPerformed(ActionEvent e) {
        try {
          StringBuilder sb = new StringBuilder();
          File file = new File(controller.getSettings().getScreenSettings());
          file.delete();
          BufferedWriter writer = new BufferedWriter(new FileWriter(file));
          sb.append(leftUpper.getText());
          sb.append(",");
          sb.append(rightLower.getText());

          writer.append(sb.toString());
          screenCoords = sb.toString();
          writer.close();
          JOptionPane.showMessageDialog(null, "Done!");
        } catch (Exception ex) {
          JOptionPane.showMessageDialog(null, "Error!");
          System.out.println(ex);
          ex.printStackTrace();
        }
      }
    };
  }

  private String initLeft() {
    if (screenCoords == null) {
      return "0,0";
    }
    try {
      String[] coords = screenCoords.trim().split(",");
      return coords[0] + "," + coords[1];
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "Error parsing screen coordinates settings!");
      System.out.println(e);
      return "0,0";
    }
  }

  private String initRight() {
    if (screenCoords == null) {
      return "0,0";
    }
    try {
      String[] coords = screenCoords.trim().split(",");
      return coords[2] + "," + coords[3];
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "Error parsing screen coordinates settings!");
      System.out.println(e);
      return "0,0";
    }
  }
}
